<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\NewRoles;
use App\Services\UserService;
use Illuminate\Http\Request;

/**
 * 用户数据
 */
class UserController extends Controller
{
    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    /**
     * 列表
     *
     * @return void
     */
    public function index(Request $request)
    {
        $page = [
            'page_name' => 'user',
            'title' => '账号管理',
            'breadcrumb' => [
                [
                    'text' => '权限管理',
                    'url' => 'javascript:void(0)'
                ]
            ],
        ];
        $userModel = Admin::whereNotIn('user_type', [2, 3]);
        $value = trim($request->input("value"));
        if (!empty($value)) {
            $userModel->where(function ($query) use ($value) {
                foreach (['unique_id', 'abbr', 'phone_number'] as $c) {
                    $query->orWhere($c, 'like', '%'.$value.'%');
                }
            });
        }
        if (!empty($request->input('status'))) {
            $userModel->where('status', $request->input('status'));
        }

        $users = $userModel->paginate(50);
        $roles = NewRoles::where('status', 1)->get();
        $data = [];
        foreach ($roles as $role) {
            $data[$role['id']] = $role;
        }

        return view('admin.new_users.index', 
        [
            'data' => $users, 'roles' => $data, 'page' => $page
        ]);
    }

    public function create(Request $request)
    {
        $page = [
            'page_name' => 'user',
            'title' => '添加账号',
            'breadcrumb' => [
                [
                    'text' => '账号管理',
                    'url' => '/admin/user'
                ]
            ],
        ];
        $roles = NewRoles::where('status', 1)->get();
        $distributions = Admin::where("user_type", 2)->get();
        $data = new Admin();
        $accountId = (new UserService())->createAccountId();
        return view('admin.new_users.create',
        [
           'roles' => $roles,
            'distributions' => $distributions,
            'page'  => $page,
            'data' => $data,
            'accountId' => $accountId,
        ]);
    }

    public function add(Request $request)
    {
        $unique_id = trim($request->input('unique_id'));
        $user = Admin::where("unique_id", $unique_id)->first();
        if (!empty($user)) {
            return redirect('/'.$request->path().'/')->with('trash', '增加账号失败');
        }

        $password = trim($request->input('password'));
        $ulen = mb_strlen($unique_id);

        $unique_id = str_replace(' ', '', $unique_id);
        $unique_id = strtoupper($unique_id);

        if ($ulen >9) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'账号不符合规则']);
        }
        if (mb_strlen($password) < 7) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'密码设置不得低于6位！']);
        }

        $mod = new Admin();
        $mod->unique_id = $unique_id;
        $mod->password = bcrypt($password); // $password
        if (empty($mod->unique_id)) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'账号不能为空!']);
        }
        if (empty($mod->password)) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'密码不能为空!']);
        }
        $mod->abbr = trim($request->input('abbr'));
        $mod->first_name = trim($request->input('first_name'));
        $mod->email_address = trim($request->input('email_address'));
        $mod->phone_number = trim($request->input('phone_number'));
        $mod->cell_phone = trim($request->input('cell_phone'));
        $mod->wechat_id = trim($request->input('wechat_id'));
        $mod->creator_id = (int) $request->input('creator_id');
        $mod->role_id = (int) $request->input('role_id');
        $mod->last_name = '';
        $mod->username = '';
        $mod->zip = 0;
        $mod->date_signedup = date('Y-m-d H:i:s');
        $mod->additional_comment = '';
        $mod->status = (int) $request->input('status');
        $extension = trim($request->input('extension'));
        $mod->extension = $extension;
        $mod->creator_id = 0;
        $mod->user_type = !empty($request->input('distributions_id')) ? 4 : 1;
        $mod->note = trim($request->input('note') ?: '');
        $mod->created_by = session('admin.id');
        $result = $mod->save();
        if ($result && !empty($request->input('distributions_id'))) {
            $distributions_id = !is_array($request->input('distributions_id')) ? [$request->input('distributions_id')] : $request->input('distributions_id');
            $this->userService->saveUserRelation($mod->id, $distributions_id);
        }

        return redirect('/'.$request->path().'/')->with('trash', '账号创建成功');
    }

    public function editStatus(Request $request)
    {
        $id = $request->input('id');
        $mod = Admin::findOrFail($id);
        $mod->status = (int) (!$mod->status);
        $mod->save();
        editUserStatus($mod);
        session()->flash('hightlight', ['id'=>$id, 'type'=>'user']);
        return ['status'=>'SUCCESS'];
    }

    public function edit(Request $request)
    {
        $page = [
            'page_name' => '账号',
            'title' => '编辑用户',
            'breadcrumb' => [
                [
                    'text' => '用户管理',
                    'url' => '/admin/user'
                ]
            ],
        ];
        $user = Admin::where('id', $request->input('id'))->first();
        $roles = NewRoles::where('status', 1)->get();
        $distributions = Admin::where("user_type", 2)->get();
        if ($user->user_type == 4) {
            $distribution_ids = $this->userService->getDistributions(4, $user->id);
        }
        $allDistributions = [];
        foreach ($distributions as $item) {
            $allDistributions[] = $item->id;
        }

        return view('admin.new_users.edit', [
            'user' => $user,
            'roles' => $roles,
            'distributions' => $distributions,
            'userDistributions' => $distribution_ids ?? [],
            'all_selected' => $allDistributions == ($distribution_ids ?? []) ? 1 : 0,
            'page'  => $page,
        ]);
    }

    public function editUser(Request $request)
    {
        $id = $request->input('id');
        $unique_id = trim($request->input('unique_id'));

        $password = trim($request->input('password'));
        $ulen = mb_strlen($unique_id);

        $unique_id = str_replace(' ', '', $unique_id);
        $unique_id = strtoupper($unique_id);

        if (!empty($unique_id) && $ulen >9) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'账号不符合规则']);
        }
        if (!empty($password) && mb_strlen($password) < 7) {
            return redirect()-> back()->withInput()->with('trash', ['type'=>'error', 'content'=>'密码设置不得低于6位！']);
        }

        $mod = Admin::find($id);
        if (!empty($password)) {
            $mod->password = bcrypt($password);
        }
        if (!empty($mod->unique_id)) {
            $mod->unique_id = $unique_id;
        }
        $mod->abbr = trim($request->input('abbr'));
        $mod->first_name = trim($request->input('first_name'));
        $mod->email_address = trim($request->input('email_address'));
        $mod->phone_number = trim($request->input('phone_number'));
        $mod->cell_phone = trim($request->input('cell_phone'));
        $mod->wechat_id = trim($request->input('wechat_id'));
        $mod->creator_id = (int) $request->input('creator_id');
        $mod->role_id = (int) $request->input('role_id');
        $mod->last_name = '';
        $mod->username = '';
        $mod->zip = 0;
        $mod->date_signedup = date('Y-m-d H:i:s');
        $mod->additional_comment = '';
        $mod->status = (int) $request->input('status');
        $extension = trim($request->input('extension'));
        $mod->extension = $extension;
        $mod->creator_id = 0;
        $mod->user_type = !empty($request->input('distributions_id')) ? 4 : 1;
        $mod->note = trim($request->input('note') ?: '');

        $mod->created_by = session('admin.id');
        $result = $mod->save();
        if ($result && !empty($request->input('distributions_id'))) {
            $distributions_id = !is_array($request->input('distributions_id')) ? [$request->input('distributions_id')] : $request->input('distributions_id');
            $this->userService->saveUserRelation($mod->id, $distributions_id);
        }

        return redirect('/admin/user/')->with('trash', '账号更新成功');
    }
}